package com.syh.jn.scm.domain.supplier.entity.purchase;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.spring.SpringContextUtils;
import cn.redscarf.commons.util.validator.ValidationUtils;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.domain.CodeExpEnum;
import com.syh.core.ddd.domain.CodeGenerateUtil;
import com.syh.jn.scm.domain.supplier.entity.logistics.LogisticsBill;
import com.syh.jn.scm.domain.supplier.repository.logistics.LogisticsBillReadRepository;
import com.syh.jn.scm.domain.support.SuperBusinessAggregate;
import com.syh.jn.scm.dto.supplier.purchase.PurchaseReturnOrderMto;
import com.syh.jn.scm.dto.supplier.purchase.PurchaseReturnOrderSto;
import com.syh.jn.scm.dto.support.FilesDto;
import com.syh.jn.scm.exception.BusinessException;
import com.syh.jn.scm.service.api.supplier.logistics.enums.LogisticsBillEnums;
import com.syh.jn.scm.service.api.supplier.purchase.enums.PurchaseOrderEnums;
import com.syh.jn.scm.service.api.supplier.purchase.enums.PurchaseReturnOrderEnums;
import com.syh.jn.scm.service.api.supplier.sale.enums.SaleReturnOrderEnums;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购退货单聚合
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class PurchaseReturnOrder extends SuperBusinessAggregate<Long> {
  public PurchaseReturnOrder(Long id) {
    this.id = id;
  }

  /**
   * 采购退货单新增
   *
   * @param sto
   */
  public PurchaseReturnOrder(PurchaseReturnOrderSto sto) {
    ExtAssert.notNull(sto, "对象为空");
    ValidationUtils.validate(sto);
    this.returnCode = CodeGenerateUtil.codeGenerate(CodeExpEnum.PURCHASE_RETURN_ORDER_EXP.getCodeExp(), sto.getUpStreamCompanyId());
    //优惠
    this.discount = BigDecimal.ZERO;
    //设置订单为待确认
    this.returnOrdState = PurchaseReturnOrderEnums.OrdState.STAYCONFIRM.getStatus();
    super.initDefault();
    //未生成物流单
    this.generatedState = PurchaseReturnOrderEnums.GeneratedState.LOGISTICS_UN_GENERATE.getStatus();
    //未发车
    this.deliveryState = PurchaseReturnOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus();
    //未签收
    this.collectState = PurchaseReturnOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus();
    //运费总额默认初始化为0
    this.totalFreight = BigDecimal.ZERO;
    this.haveRecord = PurchaseOrderEnums.OrdState.NOT_RECORD.getStatus();
    ExtBeanUtils.copyProperties(sto, this, false);
    this.items = new ArrayList<>();
    //添加订单项
    sto.getItems().forEach(item -> {
      this.addItem(new PurchaseReturnOrderItem(item));
    });
    //计算订单退货总额
    calculateTotalAmount();
  }

  /**
   * 计算订单退货总额、商品总额
   */
  private void calculateTotalAmount() {
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (PurchaseReturnOrderItem item : this.items) {
      totalAmount = totalAmount.add(item.getReturnTotalAmount());
    }
    this.returnTotalGoodsAmount = totalAmount;//退货订单商品总额
    //减去优惠价格
    if (this.discount != null) {
      totalAmount = totalAmount.subtract(this.discount);
    }
    //退货订单总额
    this.returnTotalAmount = totalAmount;

  }

  /**
   * 计算订单出库总额、商品出库总额
   * type: 0为发货，1为取消发货
   */
  private void calculateTotalReturnOutAmount() {
    //累计订单项发货商品总额
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (PurchaseReturnOrderItem item : this.items) {
      totalAmount = totalAmount.add(item.calculateTotalReturnOutAmount());
    }
    //计算订单已出库订单总额、已出库商品总额
    this.returnTotalOutGoodsAmount = totalAmount;

    //先计算出该订单下已发出、已签收状态的物流单据的物流费用
    LogisticsBillReadRepository logisticsBillReadRepository = (LogisticsBillReadRepository) SpringContextUtils.getBean(LogisticsBillReadRepository.class);
    Wrapper we = Wrapper.build();
    we.append(Restrictions.eq("orderId", this.id));
    we.append(Restrictions.eq("orderType", LogisticsBillEnums.OrderType.RETURN_PURCHASE.getStatus()));
    we.append(Restrictions.or(Restrictions.eq("logisticsState", LogisticsBillEnums.State.DELIVEED.getStatus()),
            Restrictions.eq("logisticsState", LogisticsBillEnums.State.SIGNIN.getStatus())));
    List<LogisticsBill> logisticsBills = logisticsBillReadRepository.getList(we);

    BigDecimal logisticsBillBeforeBuyFreight = BigDecimal.ZERO;//物流单据为预收买家的所有物流费用
    for (LogisticsBill logisticsBill : logisticsBills) {
      if (logisticsBill.getFreightTake() != null && logisticsBill.getFreightTake().equals(LogisticsBillEnums.FreightTake.BUY.getStatus())
              && logisticsBill.getFreightType().equals(LogisticsBillEnums.FreightType.BEFORE.getStatus()))
        logisticsBillBeforeBuyFreight = logisticsBillBeforeBuyFreight.add(logisticsBill.getTotalFreight());
    }

    //减去优惠金额
    if (this.discount != null) {
      totalAmount = totalAmount.subtract(this.discount);
    }
    //加上预收买家的运费
    totalAmount = totalAmount.add(logisticsBillBeforeBuyFreight);
    this.returnTotalOutAmount = totalAmount.compareTo(BigDecimal.ZERO) < 1 ? BigDecimal.ZERO : totalAmount;
    this.totalFreight = logisticsBillBeforeBuyFreight;
    this.lastUpdateTimeStamp = System.currentTimeMillis();

  }

  /**
   * 计算订单出库状态
   */
  private void calculateDeliveryStatus() {

    this.deliveryState = PurchaseReturnOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus();
    //默认标记为未发货
    boolean unDelivery = true;
    //计算订单发货状态
    for (PurchaseReturnOrderItem item : this.items) {
      //订单项已发货数量小于订单数量则为部分发货
      if (this.deliveryState.equals(PurchaseReturnOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus())
              && item.getReturnOutedQuantity().compareTo(item.getReturnQuantity()) < 0) {
        this.deliveryState = PurchaseReturnOrderEnums.DeliveryState.LOGISTICS_PART_DELIVEED.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unDelivery && item.getReturnOutedQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unDelivery = false;
      }
    }
    if (unDelivery) {
      this.deliveryState = PurchaseReturnOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus();
      this.deliveryTimestamp = null;
    }
  }

  //添加订单项
  private PurchaseReturnOrder addItem(PurchaseReturnOrderItem item) {
    if (this.items == null) {
      this.items = new ArrayList<>();
    }
    this.items.add(item);
    return this;
  }

  /**
   * 校验订单是否存在
   *
   * @param purchaseReturnOrder
   */
  public void check(PurchaseReturnOrder purchaseReturnOrder) {
    if (purchaseReturnOrder == null) {
      throw new BusinessException("订单不存在");
    }
  }

  /**
   * 修改采购退货订单
   *
   * @param mto
   */
  public void modify(PurchaseReturnOrderMto mto) {
    ExtAssert.notNull(mto, "对象为空");
    ValidationUtils.validate(mto);
    if (this.getReturnOrdState().equals(PurchaseReturnOrderEnums.OrdState.CONFIRM.getStatus())) {
      throw new BusinessException("订单已经确认,不可以修改");
    }
    ExtBeanUtils.copyProperties(mto, this);
    this.lastUpdateTimeStamp = System.currentTimeMillis();
    this.items = new ArrayList<>();
    mto.getItems().stream().forEach(itemMto -> {
      this.addItem(new PurchaseReturnOrderItem(itemMto));
    });
    //重新计算
    this.calculateTotalAmount();
  }

  /**
   * 取消订单
   */
  public void cancel() {
    //只有订单为空待确认的时候才可以取消
    if (this.returnOrdState.equals(PurchaseReturnOrderEnums.OrdState.STAYCONFIRM.getStatus())) {
      this.returnOrdState = PurchaseReturnOrderEnums.OrdState.CANCEL.getStatus();
    } else {
      throw new BusinessException("订单不是待确认状态,不可以取消");
    }
  }

  /**
   * 上传图片
   *
   * @param dto
   */
  public void upload(FilesDto dto) {
    this.mainSrcImages = dto.getFiles();
  }


  /**
   * 记录已生成物流数量
   *
   * @param logisticsBill
   * @param operate       (1为增加记录，2为减少记录)
   */
  public void countGeneratedQuantity(LogisticsBill logisticsBill, int operate) {
    if (operate == 1) {
      logisticsBill.getItems().forEach(logisticsBillItem -> {
        this.items.forEach(orderItem -> {
          if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
            orderItem.setGeneratedQuantity(orderItem.getGeneratedQuantity() == null ? logisticsBillItem.getQuantity() :
                    orderItem.getGeneratedQuantity().add(logisticsBillItem.getQuantity()));
            //如果当前生成发货数量大于退货总数 则不允许生成
            if (orderItem.getGeneratedQuantity().compareTo(orderItem.getReturnQuantity()) > 0) {
              throw new BusinessException("发货失败：超出退货数量！"+orderItem.getGoodsName()+"退货数量"+orderItem.getReturnQuantity()+";已退货数量"+orderItem.getGeneratedQuantity().subtract(logisticsBillItem.getQuantity()));
            }
          }
        });
      });
    } else {
      logisticsBill.getItems().forEach(logisticsBillItem -> {
        this.items.forEach(orderItem -> {
          if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
            orderItem.setGeneratedQuantity(orderItem.getGeneratedQuantity().subtract(logisticsBillItem.getQuantity()));
          }
        });
      });
    }

    //默认为已完全生成物流单
    this.generatedState = PurchaseReturnOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus();
    //默认标记为未生成物流单
    boolean unGenerated = true;

    for (PurchaseReturnOrderItem item : this.items) {
      //订单项已生成数量小于订单数量则为部分生成物流单
      if (this.generatedState.equals(PurchaseReturnOrderEnums.GeneratedState.LOGISTICS_WHOLE_GENERATE.getStatus())
              && item.getGeneratedQuantity().compareTo(item.getReturnQuantity()) < 0) {
        this.generatedState = PurchaseReturnOrderEnums.GeneratedState.LOGISTICS_PART_GENERATE.getStatus();
      }
      //订单项已发货数量大于0 则不是未发货
      if (unGenerated && item.getGeneratedQuantity().compareTo(BigDecimal.ZERO) > 0) {
        unGenerated = false;
      }
    }
    if (unGenerated) {
      this.generatedState = PurchaseReturnOrderEnums.GeneratedState.LOGISTICS_UN_GENERATE.getStatus();
    }
  }

  /**
   * 删除退货订单
   */
  public void destroy() {
    if (!this.returnOrdState.equals(PurchaseReturnOrderEnums.OrdState.STAYCONFIRM.getStatus())
            && !this.returnOrdState.equals(PurchaseReturnOrderEnums.OrdState.CANCEL.getStatus())) {
      throw new BusinessException("订单不是已取消状态或待确认状态,不可以删除");
    }
    if (this.haveRecord != null &&
            this.haveRecord.equals(PurchaseReturnOrderEnums.OrdState.HAVE_RECORD.getStatus())) {
      throw new BusinessException("订单已存在记录,不可以删除");
    }
  }

  /**
   * 发货信息更新
   */
  public void delivery(LogisticsBill bill) {
    if (this.deliveryState.equals(PurchaseOrderEnums.DeliveryState.LOGISTICS_WHOLE_DELIVEED.getStatus()))
      throw new BusinessException("发货失败，已全部发货！");
    //获取物流单据明细并计算订单项的已收货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setReturnOutedQuantity(orderItem.getReturnOutedQuantity() == null ? logisticsBillItem.getQuantity() :
                  orderItem.getReturnOutedQuantity().add(logisticsBillItem.getQuantity()));
        }
      });
    });

    this.haveRecord = PurchaseOrderEnums.OrdState.HAVE_RECORD.getStatus();
    this.deliveryTimestamp = System.currentTimeMillis();
    this.calculateTotalReturnOutAmount();
    this.calculateDeliveryStatus();
  }

  /**
   * 取消发货信息更新
   */
  public void cancelDelivery(LogisticsBill bill) {
    if (this.deliveryState.equals(PurchaseOrderEnums.DeliveryState.LOGISTICS_UN_DELIVERY.getStatus()))
      throw new BusinessException("取消发货失败，无发货记录！");
    //获取物流单据明细并计算订单项的已收货数量
    bill.getItems().forEach(logisticsBillItem -> {
      this.items.forEach(orderItem -> {
        if (orderItem.getId().equals(logisticsBillItem.getOrderItemId())) {
          orderItem.setReturnOutedQuantity(orderItem.getReturnOutedQuantity() == null ? logisticsBillItem.getQuantity() :
                  orderItem.getReturnOutedQuantity().subtract(logisticsBillItem.getQuantity()));
        }
      });
    });

    this.calculateTotalReturnOutAmount();
    this.calculateDeliveryStatus();
  }

  /**
   * 生成对账单
   */
  public void generating(Long statementOfAccountId) {
    if (this.collectState.equals(PurchaseReturnOrderEnums.CollectState.LOGISTICS_UN_COLLECT.getStatus())) {
      throw new BusinessException("采购退货单" + this.returnCode + "未签收，无法生成对账单");
    }
    if (this.returnOrdState.equals(PurchaseReturnOrderEnums.OrdState.STATEMENT.getStatus())) {
      throw new BusinessException("采购退货单已生成对账单!");
    }
    this.statementId = statementOfAccountId;
    this.returnOrdState = PurchaseReturnOrderEnums.OrdState.STATEMENT.getStatus();
  }

  /**
   * 取消对账单
   */
  public void cancelGenerating() {
    if (this.returnOrdState.equals(SaleReturnOrderEnums.State.CONFIRM.getStatus())) {
      throw new BusinessException("采购退货单已取消对账单!");
    }
    this.statementId = null;
    this.returnOrdState = PurchaseReturnOrderEnums.OrdState.CONFIRM.getStatus();
  }

  /**
   * 确认
   */
  public void confirm() {
    if (this.getReturnOrdState().equals(PurchaseReturnOrderEnums.OrdState.STAYCONFIRM.getStatus())) {
      this.returnOrdState = PurchaseReturnOrderEnums.OrdState.CONFIRM.getStatus();
    } else {
      throw new BusinessException("订单不是待确认状态,不能确认订单");
    }
  }

  /**
   * 采购退货订单编号
   */
  private String returnCode;
  /**
   * 第三方单号
   */
  private String extCode;
  /**
   * 对应采购订单id
   */
  private Long purchaseOrderId;
  /**
   * 上游供应商id
   */
  private Long upStreamCompanyId;
  /**
   * 采购退货订单状态(0：待确认 1：已确认 2：挂起 3:已生成对账单 -1：已取消)
   */
  private Short returnOrdState;
  /**
   * 采购退货原因(字典拿的数据)
   */
  private Long returnReasonId;
  /**
   * 收货人姓名
   */
  private String deliName;
  /**
   * 收货人联系电话
   */
  private String deliTel;
  /**
   * 运费金额
   */
  private BigDecimal totalFreight;
  /**
   * 收货地区编码
   */
  private String deliAreaCode;
  /**
   * 收货地址省 市 区
   */
  private String deliArea;
  /**
   * 收货人详细地址
   */
  private String deliAddress;
  /**
   * 发货地区编码
   */
  private String retDeliAreaCode;
  /**
   * 发货地址省 市 区
   */
  private String retDeliArea;
  /**
   * 发货人详细地址
   */
  private String retDeliAddress;
  /**
   * 备注
   */
  private String remark;
  /**
   * 录单人员id
   */
  private Long operatorId;
  /**
   * 物流生成状态(0：未生成物流单 1：部分生成物流单2：完成生成物流单)
   */
  private Short generatedState;
  /**
   * 发货状态(0：未发货 1：部分发货 2：完成发货)
   */
  private Short deliveryState;
  /**
   * 签收状态(0：未签收 1：部分签收 2：完成签收)
   */
  private Short collectState;
  /**
   * 退货订单总额
   */
  private BigDecimal returnTotalAmount;
  /**
   * 退货订单商品总额
   */
  private BigDecimal returnTotalGoodsAmount;
  /**
   * 退货出库总额
   */
  private BigDecimal returnTotalOutAmount;
  /**
   * 退货出库商品总额
   */
  private BigDecimal returnTotalOutGoodsAmount;
  /**
   * 退货签收总额
   */
  private BigDecimal returnTotalInAmount;
  /**
   * 退货签收商品总额
   */
  private BigDecimal returnTotalInGoodsAmount;
  /**
   * 优惠减免
   */
  private BigDecimal discount;
  /**
   * 对账单id
   */
  private Long statementId;
  /**
   * 录单日期
   */
  private Long inputDateTimestamp;
  /**
   * 发货时间(出库)
   */
  private Long deliveryTimestamp;
  /**
   * 收货时间
   */
  private Long receiptTimestamp;
  /**
   * 我方单据图片
   */
  private String mainSrcImages;
  /**
   * 对方单据图片
   */
  private String secondSrcImages;
  /**
   * 是否已生成记录(库存记录、应收付记录等) 0:未生成 1：已生成
   */
  private Short haveRecord;
  /**
   * 采购退货单明细
   */
  protected List<PurchaseReturnOrderItem> items;

}
